package com.zhongxi.guoyuan.view;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.text.Html;
import android.text.TextUtils;
import android.util.Log;
import android.util.Xml;
import android.view.View;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.zhongxi.guoyuan.R;
import com.zhongxi.guoyuan.adapter.ImageQrAdapter;
import com.zhongxi.guoyuan.application.MyApplication;
import com.zhongxi.guoyuan.base.BaseActivity;
import com.zhongxi.guoyuan.entity.BaseResponse;
import com.zhongxi.guoyuan.entity.QRBean.QrCodeinfo;
import com.zhongxi.guoyuan.entity.QRBean.QrOrderInfo;
import com.zhongxi.guoyuan.entity.QRBean.QrToPay;
import com.zhongxi.guoyuan.entity.pay.PayAliPayData;
import com.zhongxi.guoyuan.entity.pay.WeixinData;
import com.zhongxi.guoyuan.entity.shopcart.RewardSummary;
import com.zhongxi.guoyuan.url.Url;
import com.zhongxi.guoyuan.utils.CommonTool;
import com.zhongxi.guoyuan.utils.Constants;
import com.zhongxi.guoyuan.utils.DataUtil;
import com.zhongxi.guoyuan.utils.DesTool;
import com.zhongxi.guoyuan.utils.ImageUtils;
import com.zhongxi.guoyuan.utils.MD5Tool;
import com.zhongxi.guoyuan.utils.PayUtils;
import com.zhongxi.guoyuan.utils.ToastUtil;
import com.zhongxi.guoyuan.utils.UiUtils;
import com.zhongxi.guoyuan.weixin.MD5;
import com.zhongxi.guoyuan.weixin.Util;
import com.zhongxi.guoyuan.widget.CircleIndicator;
import com.zhongxi.guoyuan.widget.ViewFlow;
import com.zhongxi.guoyuan.widget.screenadaptaion.CustomLinearlayout;
import com.zhongxi.guoyuan.zhifubao.PayResult;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import org.xmlpull.v1.XmlPullParser;

import java.io.StringReader;
import java.math.BigDecimal;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Random;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;


/**
 * Created by Administrator on 2017/11/16.
 */

public class QrOrderActivity extends BaseActivity {
    @Bind(R.id.ivBack)
    ImageView ivBack;
    @Bind(R.id.tvTitle)
    TextView tvTitle;
    @Bind(R.id.flow)
    FrameLayout flow;
    @Bind(R.id.viewflow)
    ViewFlow viewFlow;
    @Bind(R.id.viewflowdic)
    CircleIndicator viewflowdic;
    @Bind(R.id.tv_goodId)
    TextView tvGoodId;
    @Bind(R.id.tv_goodName)
    TextView tvGoodName;
    @Bind(R.id.tv_attr)
    TextView tvAttr;
    @Bind(R.id.tv_price)
    TextView tvPrice;
    @Bind(R.id.tv_award)
    TextView tvAward;
    @Bind(R.id.tv)
    TextView tv;
    @Bind(R.id.tv_reward_price)
    TextView tvRewardPrice;
    @Bind(R.id.tv_total_award)
    TextView tvTotalAward;
    @Bind(R.id.iv_weixin)
    ImageView ivWeixin;
    @Bind(R.id.iv_zhifubao)
    ImageView ivZhifubao;
    @Bind(R.id.relaBottom)
    CustomLinearlayout relaBottom;
    @Bind(R.id.tvSub)
    TextView tvSub;
    @Bind(R.id.etNum)
    EditText etNum;
    @Bind(R.id.tvAdd)
    TextView tvAdd;
    @Bind(R.id.tv_case)
    TextView tvCase;
    @Bind(R.id.tv_total_case)
    TextView tvTotalCase;
    private String codeinfo;
    private Map<String, String> map = new HashMap<>();
    private String type;
    private String safeKey;
    private String cartificate;
    private ImageQrAdapter mBannerAdapter;
    private int index;
    private QrOrderInfo data;
    private String orderId;
    private PayAliPayData aliPayData;
    private WeixinData weixinData;
    private RewardSummary rewardSummary;

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    PayResult payResult = new PayResult((String) msg.obj);
                    /**
                     * 对于支付结果，请商户依赖服务端的一部通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();//同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    //判断resultStatus为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        //该笔订单是否真实支付成功，需要依赖服务端的异步通知
                        Intent intent = new Intent(context, PaySuccessActivity.class);
                        intent.putExtra("rewardPrice", rewardSummary.getPrice());
                        intent.putExtra("status", 1);
                        startActivity(intent);
                    } else {
                        Intent intent = new Intent(context, PaySuccessActivity.class);
                        intent.putExtra("orderid", orderId);
                        intent.putExtra("certificate", certificate);
                        startActivity(intent);
                    }
                    break;
            }
        }
    };
    private IWXAPI msgApi;
    private PayReq req;
    private StringBuffer sb;
    private Map<String, String> resultunifiedorder;
    private String trim;
    private int num = 1;
    private String certificate;

    @Override
    protected void initView() {
        super.initView();
        setContentView(R.layout.activity_qr_pay);
        ButterKnife.bind(this);
        codeinfo = getIntent().getStringExtra("codeinfo");
        tvTitle.setText("当面付");
        ImageUtils.setHeight(this, Constants.flowRate, flow);
    }

    @Override
    protected void initData() {
        super.initData();
        map.clear();
        map.put("codeinfo", codeinfo);
        type = "codeinfo";
        getServer(Url.QRCODEINFO, map, "", false, null, "post");
    }

    @OnClick({R.id.ivBack, R.id.iv_weixin, R.id.iv_zhifubao, R.id.tvSub, R.id.etNum, R.id.tvAdd})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ivBack:
                finish();
                break;
            case R.id.iv_weixin:
                if (!TextUtils.isEmpty(MyApplication.getInstance().getPhone())) {
                    if (CommonTool.isFirstLongScroll()) {
                        index = 0;
                        getToPay();
                    }
                } else {
                    ToastUtil.show("您还没有绑定手机号,暂无法支付");
                }
                break;
            case R.id.iv_zhifubao:
                if (!TextUtils.isEmpty(MyApplication.getInstance().getPhone())) {
                    if (CommonTool.isFirstLongScroll()) {
                        index = 1;
                        getToPay();
                    }
                } else {
                    ToastUtil.show("您还没有绑定手机号,暂无法支付");
                }
                break;
            case R.id.tvSub:
                trim = etNum.getText().toString().trim();
                if (null != trim && !"".equals(trim)) {
                    if (Integer.parseInt(trim) > 1) {
                        num = Integer.parseInt(trim);
                        num--;
                        etNum.setText(num + "");
                    }
                }
                refresh();
                break;
            case R.id.etNum:
                break;
            case R.id.tvAdd:
                trim = etNum.getText().toString().trim();
                if (null != trim && !"".equals(trim)) {
                    num = Integer.parseInt(trim);
                    num++;
                    etNum.setText(num + "");

                }
                refresh();
                break;
        }
    }

    private void refresh() {
        switch (data.getGoodstype()) {
            case 1:
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                    tvTotalAward.setText(Html.fromHtml("<font color='#ff7f00'>" + context.getResources().getString(R.string.give_meidou) + CommonTool.getWhole(DataUtil.multiplys(data.getPrice(), num + "", 2))
                            + " 美豆+</font><font color='#ff4c4c'>" + DataUtil.multiplys(DataUtil.multiplys(data.getPrice(), num + "", 2), "0.05", 2) + "红豆</font>", Html.FROM_HTML_MODE_COMPACT));
                } else {
                    tvTotalAward.setText(Html.fromHtml("<font color='#ff7f00'>" + context.getResources().getString(R.string.give_meidou) + CommonTool.getWhole(DataUtil.multiplys(data.getPrice(), num + "", 2))
                            + " 美豆+</font><font color='#ff4c4c'>" + DataUtil.multiplys(DataUtil.multiplys(data.getPrice(), num + "", 2), "0.05", 2) + "红豆</font>"));
                }
                break;
            case 3:
                String mMultiplys = DataUtil.multiplys(data.getPrice(), num + "", 2);
                tvTotalAward.setText("奖 " + CommonTool.getWhole(DataUtil.multiplys(mMultiplys, "0.1", 4)) + " 红豆");
                tvTotalCase.setText(UiUtils.getString(R.string.goldenDesc) + mMultiplys + "元");
                break;
        }
        tvRewardPrice.setText(DataUtil.multiplys(data.getPrice(), num + "", 2) + " 元");
    }

    private void getToPay() {
        map.clear();
        map.put("goodsnum", num + "");
        map.put("safeKey", safeKey);
        map.put("certificate", cartificate);
        type = "topay";
        getServer(Url.QRTOPAY, map, "", false, null, "post");
    }

    @Override
    protected void processSuccessResult(String response) {
        super.processSuccessResult(response);
        Gson gson = new Gson();
        try {
            if ("codeinfo".contains(type)) {
                System.out.println("codeinfo==" + response);
                QrCodeinfo qrCodeinfo = gson.fromJson(response, QrCodeinfo.class);
                MyApplication.getInstance().setSpValue(qrCodeinfo.getSafeobj());
                if (null != qrCodeinfo.getSafeKey() && !"".equals(qrCodeinfo.getSafeKey())) {
                    safeKey = qrCodeinfo.getSafeKey();
                }
                if (null != qrCodeinfo.getCertificate() && !"".equals(qrCodeinfo.getCertificate())) {
                    cartificate = qrCodeinfo.getCertificate();
                }
                JSONObject object = new JSONObject(response);
                JSONObject jsonObject = object.optJSONObject("data");
                List<String> attrList = new ArrayList<>();
                if (null != jsonObject && !"".equals(jsonObject)) {
                    JSONObject attr = jsonObject.optJSONObject("attr");
                    if (null != attr && attr.length() > 0) {
                        Iterator<String> keys = attr.keys();
                        while (keys.hasNext()) {
                            String next = keys.next();
                            attrList.add(attr.optString(next));
                        }
                    }
                }
                if (null != qrCodeinfo.getData() && !"".equals(qrCodeinfo.getData())) {
                    data = qrCodeinfo.getData();
                    getInitInfo(attrList);
                }
            } else if ("topay".equals(type)) {
                QrToPay qrToPay = gson.fromJson(response, QrToPay.class);
                MyApplication.getInstance().setSpValue(qrToPay.getSafeobj());
                if (!TextUtils.isEmpty(qrToPay.getCertificate())) {
                    certificate = qrToPay.getCertificate();
                }
                JSONObject baseObject = new JSONObject(response);
                orderId = baseObject.optString("orderid");
                if (qrToPay.getSecurityKey() != null && !"".equals(qrToPay.getSecurityKey())) {
                    String payParams = parseSecutiryKey(qrToPay.getSecurityKey());
                    JSONObject jsonObject = new JSONObject(payParams);
                    JSONObject alipay = jsonObject.optJSONObject("alipay");
                    aliPayData = PayAliPayData.parseObject(alipay);
                    JSONObject wechat = jsonObject.optJSONObject("wechat");
                    weixinData = WeixinData.parseObject(wechat);
                    //                    paramsResult = gson.fromJson(payParams, PayParamsResult.class);
                }
                if (null != qrToPay.getSummary() && !"".equals(qrToPay.getSummary())) {
                    String summary = MyApplication.getInstance().parseSecutiryKey(qrToPay.getSummary());
                    JSONObject object = new JSONObject(summary);
                    rewardSummary = RewardSummary.parseObject(object);
                    //                    rewardSummary = gson.fromJson(summary, RewardSummary.class);
                }
                MyApplication.getInstance().sharedPrefrences.edit().putString("pay", "facetoface").commit();
                if (index == 0) {//微信支付
                    MyApplication.getInstance().sharedPrefrences.edit().putString("orderId", orderId).commit();
                    MyApplication.getInstance().sharedPrefrences.edit().putString("certificate", certificate).commit();
                    MyApplication.getInstance().sharedPrefrences.edit().putString("rewardPrice", rewardSummary.getPrice()).commit();

//                    weixinPay(weixinData);
                    weixinPayRequest();
                } else if (index == 1) {      //支付宝支付
                    zhifubaoPayRequest();
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    /**
     * 解析后台返回的支付商户信息
     *
     * @param securityKey
     */
    private String parseSecutiryKey(String securityKey) {
        String jsonStr = "";
        try {
            String sourcestr = MD5Tool.Md5(MyApplication.getInstance().getSk() + MyApplication.getInstance().getNow());
            String strs = URLDecoder.decode(securityKey, "UTF-8");
            jsonStr = DesTool.splitdecode(sourcestr, strs);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return jsonStr;
    }

    private void getInitInfo(List<String> attrList) {
        List<String> adData = data.getImages();
        viewFlow.setFlowIndicator(viewflowdic);
        if (adData.size() > 0) {
            viewFlow.setSideBuffer(adData.size());// 实际图片数量
        } else {
            viewFlow.setSideBuffer(1);
        }
        if (mBannerAdapter == null) {
            mBannerAdapter = new ImageQrAdapter(context, adData);
        } else {
            mBannerAdapter.replaceAll(adData);
        }
        viewFlow.setAdapter(mBannerAdapter);
        viewFlow.startAutoFlowTimer();
        tvGoodId.setText("商品编号:  " + data.getId());
        tvGoodName.setText("商品名称:  " + data.getName());
        String value = "";
        if (attrList != null && attrList.size() > 0) {
            for (String str : attrList) {
                value += str + "\r\n";
            }
        }
        tvAttr.setText(value);
        tvPrice.setText("商品单价:  " + data.getPrice() + " 元");
        switch (data.getGoodstype()) {
            case 1:
                tvAward.setText(context.getResources().getString(R.string.give_meidou) + CommonTool.getWhole(data.getPrice()) + " 美豆");
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                    tvAward.setText(Html.fromHtml("<font color='#ff7f00'>" + context.getResources().getString(R.string.give_meidou) + CommonTool.getWhole(data.getPrice())
                            + " 美豆+</font><font color='#ff4c4c'>" + DataUtil.multiplys(data.getPrice(), "0.05", 2) + "红豆</font>", Html.FROM_HTML_MODE_COMPACT));
                } else {
                    tvAward.setText(Html.fromHtml("<font color='#ff7f00'>" + context.getResources().getString(R.string.give_meidou) + CommonTool.getWhole(data.getPrice())
                            + " 美豆+</font><font color='#ff4c4c'>" + DataUtil.multiplys(data.getPrice(), "0.05", 2) + "红豆</font>"));
                }
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                    tvTotalAward.setText(Html.fromHtml("<font color='#ff7f00'>" + context.getResources().getString(R.string.give_meidou) + CommonTool.getWhole(DataUtil.multiplys(data.getPrice(), num + "", 2))
                            + " 美豆+</font><font color='#ff4c4c'>" + DataUtil.multiplys(DataUtil.multiplys(data.getPrice(), num + "", 2), "0.05", 2) + "红豆</font>", Html.FROM_HTML_MODE_COMPACT));
                } else {
                    tvTotalAward.setText(Html.fromHtml("<font color='#ff7f00'>" + context.getResources().getString(R.string.give_meidou) + CommonTool.getWhole(DataUtil.multiplys(data.getPrice(), num + "", 2))
                            + " 美豆+</font><font color='#ff4c4c'>" + DataUtil.multiplys(DataUtil.multiplys(data.getPrice(), num + "", 2), "0.05", 2) + "红豆</font>"));
                }
                break;
            case 3:
                tvAward.setText("奖 " + CommonTool.getWhole(DataUtil.multiplys(data.getPrice(), "0.1", 4)) + " 红豆");
                tvCase.setText(UiUtils.getString(R.string.goldenDesc) + data.getPrice() + "元");
                String mMultiplys = DataUtil.multiplys(data.getPrice(), num + "", 2);
                tvTotalAward.setText("奖 " + CommonTool.getWhole(DataUtil.multiplys(mMultiplys, "0.1", 4)) + " 红豆");
                tvTotalCase.setText(UiUtils.getString(R.string.goldenDesc) + mMultiplys + "元");
                break;
        }
        etNum.setText(num + "");
        tvRewardPrice.setText(DataUtil.multiplys(data.getPrice(), num + "", 2) + " 元");
    }

    @Override
    protected void ProcessFailResult(String response) {
        super.ProcessFailResult(response);
        Gson gson = new Gson();
        BaseResponse baseResponse = gson.fromJson(response, BaseResponse.class);
        if (null != baseResponse.getSafeobj() && !"".equals(baseResponse.getSafeobj())) {
            MyApplication.getInstance().setSpValue(baseResponse.getSafeobj());
        }
        if (baseResponse.getCode() == 3000) {
            showShortToast("无效的二维码数据");
        } else if (baseResponse.getCode() == 3001) {
            showShortToast("二维码数据错误");
        }

    }

    private void zhifubaoPayRequest() {
        PayUtils payUtils = new PayUtils(orderId, data.getName(), 2, "", "", "", DataUtil.formatData(rewardSummary.getPrice()));
        payUtils.zhifubaoPay(aliPayData, mHandler, QrOrderActivity.this);
    }

    private void weixinPayRequest() {
        PayUtils payUtils = new PayUtils(orderId, data.getName(), 2, "", "", "", DataUtil.formatData(rewardSummary.getPrice()), this, weixinData);
        payUtils.weixinPay();
    }

    private String genOutTradNo() {
        Random random = new Random();
        return MD5.getMessageDigest(String.valueOf(random.nextInt(10000)).getBytes());
    }

    /**
     * 微信支付
     *
     * @param wechat
     */
    private void weixinPay(WeixinData wechat) {
        msgApi = WXAPIFactory.createWXAPI(this, wechat.getAppid());
        // 将该app注册到微信
        msgApi.registerApp(wechat.getAppid());
        getWXOrderInfo();
    }

    /**
     * 获取微信支付订单
     */
    private void getWXOrderInfo() {
        //正常情况下，请求服务器获取订单参数
        req = new PayReq();
        sb = new StringBuffer();
        GetPrepayIdTask getPrepayId = new GetPrepayIdTask();
        getPrepayId.execute();
    }

    private class GetPrepayIdTask extends AsyncTask<Void, Void, Map<String, String>> {

        private ProgressDialog dialog;

        @Override
        protected void onPreExecute() {
            dialog = ProgressDialog.show(context, getString(R.string.app_tip), getString(R.string.getting_prepayid));
        }

        @Override
        protected void onPostExecute(Map<String, String> result) {
            if (dialog != null) {
                dialog.dismiss();
            }
            sb.append("prepay_id\n" + result.get("prepay_id") + "\n\n");
            resultunifiedorder = result;
            genPayReq();
        }

        @Override
        protected void onCancelled() {
            super.onCancelled();
        }

        @Override
        protected Map<String, String> doInBackground(Void... params) {

            String url = String.format("https://api.mch.weixin.qq.com/pay/unifiedorder");
            String entity = genProductArgs();
            byte[] buf = Util.httpPost(url, entity);

            String content = new String(buf);
            Log.e("orion", content);
            Map<String, String> xml = decodeXml(content);

            return xml;
        }

    }

    private void genPayReq() {

        req.appId = weixinData.getAppid();
        req.partnerId = weixinData.getSeller();
        req.prepayId = resultunifiedorder.get("prepay_id");
        req.packageValue = "Sign=WXPay";
        req.nonceStr = genNonceStr();
        req.timeStamp = String.valueOf(genTimeStamp());


        List<NameValuePair> signParams = new LinkedList<NameValuePair>();
        signParams.add(new BasicNameValuePair("appid", req.appId));
        signParams.add(new BasicNameValuePair("noncestr", req.nonceStr));
        signParams.add(new BasicNameValuePair("package", req.packageValue));
        signParams.add(new BasicNameValuePair("partnerid", req.partnerId));
        signParams.add(new BasicNameValuePair("prepayid", req.prepayId));
        signParams.add(new BasicNameValuePair("timestamp", req.timeStamp));

        req.sign = genAppSign(signParams);

        sb.append("sign\n" + req.sign + "\n\n");

//        showShortToast("sb:"+sb.toString());
        Log.e("orion", signParams.toString());

        msgApi.sendReq(req);

    }

    private String genAppSign(List<NameValuePair> params) {
        StringBuilder sb = new StringBuilder();

        for (int i = 0; i < params.size(); i++) {
            sb.append(params.get(i).getName());
            sb.append('=');
            sb.append(params.get(i).getValue());
            sb.append('&');
        }
        sb.append("key=");
        sb.append(weixinData.getPartner());

        this.sb.append("sign str\n" + sb.toString() + "\n\n");
        String appSign = MD5.getMessageDigest(sb.toString().getBytes()).toUpperCase();
        Log.e("orion", appSign);
        return appSign;
    }

    private String genProductArgs() {
        StringBuffer xml = new StringBuffer();
        try {
            String nonceStr = genNonceStr();
            String trade = "";
            if ((orderId + genOutTradNo()).length() > 32) {
                trade = (orderId + genOutTradNo()).substring(0, 32);
            } else {
                trade = orderId + genOutTradNo();
            }
            xml.append("</xml>");
            List<NameValuePair> packageParams = new LinkedList<NameValuePair>();
            packageParams.add(new BasicNameValuePair("appid", weixinData.getAppid()));
            packageParams.add(new BasicNameValuePair("attach", getTimeValue() + "||" + MyApplication.getInstance().getUserId() + "||"
                    + orderId + "||2||" + DataUtil.formatData(rewardSummary.getPrice())));
            packageParams.add(new BasicNameValuePair("body", data.getName()));
            packageParams.add(new BasicNameValuePair("mch_id", weixinData.getSeller()));
            packageParams.add(new BasicNameValuePair("nonce_str", nonceStr));
            packageParams.add(new BasicNameValuePair("notify_url", Url.BASE_URL + "/notify/pay/wepay"));
            packageParams.add(new BasicNameValuePair("out_trade_no", trade));
            packageParams.add(new BasicNameValuePair("spbill_create_ip", MyApplication.getInstance().getLocalIPAddress()));
            packageParams.add(new BasicNameValuePair("total_fee", new BigDecimal(rewardSummary.getPrice()).multiply(new BigDecimal(100)).intValue() + ""));
            packageParams.add(new BasicNameValuePair("trade_type", "APP"));

            String sign = genPackageSign(packageParams);
            packageParams.add(new BasicNameValuePair("sign", sign));

            String xmlstring = toXml(packageParams);

            Log.i("base", xmlstring);
            return new String(xmlstring.toString().getBytes(), "ISO8859-1");

        } catch (Exception e) {
            Log.e("base", "" + e.getMessage());
            return null;
        }
    }

    private String toXml(List<NameValuePair> params) {
        StringBuilder sb = new StringBuilder();
        sb.append("<xml>");
        for (int i = 0; i < params.size(); i++) {
            sb.append("<" + params.get(i).getName() + ">");


            sb.append(params.get(i).getValue());
            sb.append("</" + params.get(i).getName() + ">");
        }
        sb.append("</xml>");

        Log.e("orion", sb.toString());
        return sb.toString();
    }

    public Map<String, String> decodeXml(String content) {
        try {
            Map<String, String> xml = new HashMap<String, String>();
            XmlPullParser parser = Xml.newPullParser();
            parser.setInput(new StringReader(content));
            int event = parser.getEventType();
            while (event != XmlPullParser.END_DOCUMENT) {

                String nodeName = parser.getName();
                switch (event) {
                    case XmlPullParser.START_DOCUMENT:
                        break;
                    case XmlPullParser.START_TAG:

                        if ("xml".equals(nodeName) == false) {
                            //实例化student对象
                            xml.put(nodeName, parser.nextText());
                        }
                        break;
                    case XmlPullParser.END_TAG:
                        break;
                }
                event = parser.next();
            }
            return xml;
        } catch (Exception e) {
            Log.e("orion", e.toString());
        }
        return null;

    }

    private String genNonceStr() {
        Random random = new Random();
        return MD5.getMessageDigest(String.valueOf(random.nextInt(10000)).getBytes());
    }

    private long genTimeStamp() {
        return System.currentTimeMillis() / 1000;
    }

    /**
     * 生成签名（微信）
     */

    private String genPackageSign(List<NameValuePair> params) {
        StringBuilder sb = new StringBuilder();

        for (int i = 0; i < params.size(); i++) {
            sb.append(params.get(i).getName());
            sb.append('=');
            sb.append(params.get(i).getValue());
            sb.append('&');
        }
        sb.append("key=");
        sb.append(weixinData.getPartner());

        String packageSign = MD5.getMessageDigest(sb.toString().getBytes()).toUpperCase();
        Log.e("orion", packageSign);
        return packageSign;
    }


    /**
     * 获取当前时间戳
     *
     * @return
     */
    private String getTimeValue() {
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String str = sdf.format(date);
        return str;
    }
}
